package com.ruibo.modules.quartz.service.impl;

import com.ruibo.exception.BadRequestException;
import com.ruibo.utils.PageUtil;
import com.ruibo.utils.QueryHelp;
import com.ruibo.modules.quartz.domain.QuartzJob;
import com.ruibo.modules.quartz.domain.QuartzLog;
import com.ruibo.modules.quartz.repository.QuartzJobRepository;
import com.ruibo.modules.quartz.repository.QuartzLogRepository;

import com.ruibo.modules.quartz.service.QuartzJobService;
import com.ruibo.modules.quartz.service.dto.JobQueryCriteria;
import com.ruibo.modules.quartz.utils.QuartzManage;
import org.quartz.CronExpression;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @ClassName QuartzJobServiceImpl
 * @Description QuartzJobServiceImpl
 * @Author SunFeng
 * @Date 2020/2/28 15:32
 * @Version 1.0
 */
@Service(value = "quartzJobService")
@CacheConfig(cacheNames = "quartzJob")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class QuartzJobServiceImpl implements QuartzJobService {

    private final QuartzJobRepository quartzJobRepository;

    private final QuartzLogRepository quartzLogRepository;

    private final QuartzManage quartzManage;

    public QuartzJobServiceImpl(QuartzJobRepository quartzJobRepository, QuartzLogRepository quartzLogRepository, QuartzManage quartzManage) {
        this.quartzJobRepository = quartzJobRepository;
        this.quartzLogRepository = quartzLogRepository;
        this.quartzManage = quartzManage;
    }

    @Override
    @Cacheable
    public Object queryAll(JobQueryCriteria criteria, Pageable pageable) {
        return PageUtil.toPage(quartzJobRepository.findAll((Specification<QuartzJob>) (root, query, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable));
    }

    @Override
    public List<QuartzJob> queryAll(JobQueryCriteria criteria) {
        return null;
    }

    @Override
    public Object queryAllLog(JobQueryCriteria criteria, Pageable pageable) {
        return null;
    }

    @Override
    public List<QuartzLog> queryAllLog(JobQueryCriteria criteria) {
        return null;
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public QuartzJob create(QuartzJob resources) {
        if (!CronExpression.isValidExpression(resources.getCronExpression())){
            throw new BadRequestException("cron表达式格式错误");
        }
        resources = quartzJobRepository.save(resources);
        // 每次都需要将任务添加到定时任务管理器中
        quartzManage.addJob(resources);
        return resources;
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void update(QuartzJob resources) {
        if(resources.getId().equals(1L)){
            throw new BadRequestException("该任务不可操作");
        }
        // 对Cron表达式进行验证
        if (!CronExpression.isValidExpression(resources.getCronExpression())){
            throw new BadRequestException("cron表达式格式错误");
        }
        resources = quartzJobRepository.save(resources);
        quartzManage.updateJobCron(resources);
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long[] ids) {
        // 删除需要将数据库中的数据删除 还有工作管理器中的人物删除
        for (Long id : ids) {
            if(id.equals(1L)){
                throw new BadRequestException("更新访客记录不可删除，你可以在后台代码中取消该限制");
            }
            QuartzJob quartzJob = findById(id);
            quartzManage.deleteJob(quartzJob);
            quartzJobRepository.delete(quartzJob);
        }
    }

    @Override
    public QuartzJob findById(Long id) {
        return quartzJobRepository.findById(id).orElseGet(QuartzJob::new);
    }

    @Override
    public void updateIsPause(QuartzJob quartzJob) {
        if(quartzJob.getId().equals(1L)){
            throw new BadRequestException("该任务不可操作");
        }
        //是暂停
        if (quartzJob.getIsPause()) {
            //开启作业
            quartzManage.resumeJob(quartzJob);
            //设置开启状态
            quartzJob.setIsPause(false);
        } else {
            quartzManage.pauseJob(quartzJob);
            quartzJob.setIsPause(true);
        }
        //将job进行跟新
        quartzJobRepository.save(quartzJob);
    }

    @Override
    public void execution(QuartzJob quartzJob) {
        if(quartzJob.getId().equals(1L)){
            throw new BadRequestException("该任务不可操作");
        }
        quartzManage.runJobNow(quartzJob);
    }

    @Override
    public void download(List<QuartzJob> queryAll, HttpServletResponse response) throws IOException {

    }

    @Override
    public void downloadLog(List<QuartzLog> queryAllLog, HttpServletResponse response) throws IOException {

    }
}
